package com.ruoyi.file.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.utils.MinIOUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/file")
@AllArgsConstructor
public class FileUploadController {
    private MinioConfig minioConfig;
    private MinIOUtil minIOUtil;
    @GetMapping("/bucketExists")
    public R bucketExists(@RequestParam("bucketName") String bucketName) {
        Map<String, Object> map = new HashMap<>();
        map.put("bucketExists", minIOUtil.bucketExists(bucketName));
        return R.ok(map,"查询成功");
    }

    @GetMapping("/makeBucket")
    public R makeBucket(@RequestParam("bucketName") String bucketName) {
        Map<String, Object> map = new HashMap<>();
        map.put("makeBucketok", minIOUtil.makeBucket(bucketName));
        return R.ok(map,"创建成功");
    }

    @GetMapping("/removeBucket")
    public R removeBucket(@RequestParam("bucketName") String bucketName) {
        Map<String, Object> map = new HashMap<>();
        map.put("deleteBucketok", minIOUtil.removeBucket(bucketName));
        return R.ok(map,"删除成功");
    }

    @GetMapping("/getAllBuckets")
    public R getAllBuckets() {
        Map<String, Object> map = new HashMap<>();
        map.put("buckets", minIOUtil.getAllBuckets());
        return R.ok(map,"查询成功");
    }

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        String objectName = minIOUtil.upload(file);

        if (objectName != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("url", (minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + objectName));
            return R.ok(map,"上传成功");
        }
        return R.fail("上传失败");
    }

    @GetMapping("/preview")
    public R preview(@RequestParam("fileName") String fileName) {
        Map<String, Object> map = new HashMap<>();
        map.put("url", minIOUtil.preview(fileName));
        return R.ok(map,"预览成功");
    }

    @GetMapping("/download")
    public R download(@RequestParam("fileName") String fileName, HttpServletResponse resp) {
        minIOUtil.download(fileName, resp);
        return R.ok();
    }

    @PostMapping("/delete")
    public R remove(@RequestBody Map<String, String> params) {
        String url = params.get("url");
        String objName = url.substring(url.lastIndexOf(minioConfig.getBucketName() + "/") + minioConfig.getBucketName().length() + 1);
        log.info("删除对象: {}", objName);
        minIOUtil.remove(objName);
        return R.ok("删除成功");
    }
}
